package pers.qianyu.month_202104.date_20210406;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 80. 删除有序数组中的重复项 II
 * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/
 *
 * @author mizzle rain
 * @date 2021-04-06 23:22
 */
public class RemoveDuplicates {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        if (n == 0) return n;
        Map<Integer, Integer> map = new LinkedHashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        int idx = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int key = entry.getKey();
            int val = entry.getValue() > 2 ? 2 : entry.getValue();
            for (int i = 0; i < val; i++) {
                nums[idx++] = key;
            }
        }
        return idx;
    }

    public int removeDuplicates2(int[] nums) {
        int n = nums.length;
        if (n <= 2) return n;
        int slow = 2, fast = 2;
        while (fast < n) {
            if (nums[slow - 2] != nums[fast]) {
                nums[slow] = nums[fast];
                slow++;
            }
            fast++;
        }
        return slow;
    }

    // 这样比较好理解：
    // slow 和 fast 分别指向两个数组的边界
    public int removeDuplicates3(int[] nums) {
        int n = nums.length;
        if (n <= 2) return n;

        int[] newNums = Arrays.copyOf(nums, n); // 使用 fast 遍历
        int slow = 2;// 将 nums 想象成一个空结果数组，不停的往里面填充数据
        for (int fast = 2; fast < n; fast++) {
            if (newNums[fast] == nums[slow - 2]) continue;
            nums[slow++] = newNums[fast];
        }
        return slow;
    }
}
